package com.fr.function;
import com.fr.script.AbstractFunction;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

/**
 * 帆软专用 SM4解密
 */
public class Sm4Decrypt extends AbstractFunction{
    private static final String ALGORITHM_NAME = "SM4";
    private static final String ALGORITHM_NAME_CBC = "SM4/CBC/PKCS5Padding";

    private static final byte[] KEY = "FNGdDkZBvRcBeZZYrHW3Pw==".getBytes(); // 也必须是16字节长
    private static final byte[] IV = "v3mfZaWsIRRloQ==".getBytes(); // 也必须是16字节长

    static {
        Security.addProvider(new BouncyCastleProvider());
    }


    // 解密
    public static String decrypt(String encryptedData){
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_CBC, "BC");
            byte[] decodekEY = Base64.getDecoder().decode(KEY);
            SecretKeySpec keySpec = new SecretKeySpec(decodekEY, ALGORITHM_NAME);
            IvParameterSpec ivSpec = new IvParameterSpec(IV);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes,"UTF-8");
        } catch (Exception e) {
            return encryptedData;
        }
    }


    public Object run(Object[] args) {
        return decrypt(args[0].toString());
    }
}
